package com.song.book.controller;


import com.google.code.kaptcha.Producer;


import com.song.book.utils.RedisTemplate;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class AuthController {


    @Resource
    private Producer producer;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    public String captcha(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64.getEncoder().encodeToString(outputStream.toByteArray());
//      将验证码保存到redis中，且有效时间为1分钟
        this.redisTemplate.setObject("captcha", code, 1*60L);
        return base64Img;
    }

}